import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import { Router } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
import { Subscription } from "rxjs/Subscription";
import { CmHttp } from "CmHttp";
import { SocketService } from "socket";
import { STOCKURL, LOGOS } from "shared";

import { UserService } from "user";

import { WatchlistComponent } from '../watchlist/watchlist.component';
import { StockComponent } from '../stock/stock.component';
import { QuoteComponent } from '../quote/quote.component';
import { TradeComponent } from '../trade/trade.component';
import { QuoteHeaders, TableOptions, QuoteHeader } from "./../quote/quote-table/quote-table.component";
import { BroadcastService, BROADCAST_ACTION, BROADCAST_TYPE, BROADCAST_CLASSIC_PAYLOAD } from "broadcast";
import * as _ from "lodash";
import "./app.component.html";
import "./app.component.less";

declare var UAParser;

const getParams = symbols => {
  return symbols.reduce((str, symbol) => `${str}symbol=${symbol}&`, "?");
};

@Component({
  selector: "app",
  templateUrl: "app.component.html",
  providers: [WatchlistComponent, StockComponent, QuoteComponent, TradeComponent]
})

export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
  currentTab: string;
  stockId: string = "000001_SS";
  siteLogo = LOGOS.siteLogo;
  indexStockSubscription: Subscription;
  theBigBen: Date;
  isUserLogin = false;
  modalFlag: string;

  listData = [{
    url: "/comments",
    text: "辣评",
    type: "comments",
    img: "/static/images/nav_icon_lp_default.png",
    imgActive: "/static/images/nav_icon_lp_pressed.png",
  }, {
    url: `/method`,
    text: "战法",
    type: "method",
    img: "/static/images/nav_icon_zf_default.png",
    imgActive: "/static/images/nav_icon_zf_pressed.png",
  }, {
    url: "/stock",
    text: "自选",
    type: "stock",
    img: "/static/images/nav_icon_zx_default.png",
    imgActive: "/static/images/nav_icon_zx_pressed.png",
  }, {
    url: "/quote",
    text: "行情",
    type: "quote",
    img: "/static/images/nav_icon_hq_default.png",
    imgActive: "/static/images/nav_icon_hq_pressed.png",
  }] ;

  quoteHeaders: QuoteHeaders = {
    "headHeader": undefined,
    "bodyHeader": [{
      "label": "股票名称",
      "key": "name"
    }, {
      "label": "现价",
      "key": "current",
      "withUpOrDown": true,
      "class": ["text-right"]
    }, {
      "label": "涨跌",
      "key": "change_amount",
      "withUpOrDown": true,
      "class": ["text-right"]
    }, {
      "label": "涨跌幅",
      "key": "change_rate",
      "withUpOrDown": true,
      "withPercent": true,
      "class": ["text-right"]
    }]
  };

  // foot 显示指标区域
  indexSymbolList = ["000001.SS", "399001.SZ", "399005.SZ", "399006.SZ"];
  // 用于显示的股指数据
  blockData = [];
  indexSub = new Subject();

  stockTableOptions: TableOptions = {
    autoClickFirst: false,
    subscribe: {
      enabled: true,
      channels: ["watchlist"]
    },
    responsive: {
      enabled: true,
      rowHeight: 30
    },
    parts: {
      pagination: false,
      caption: false,
      sort: false,
      header: false
    }
  };

  getSuitableClass(params: QuoteHeader, value) {
    return Object.assign({}, {
      'text-go-up': params.withUpOrDown && value >= 0,
      'text-go-down': params.withUpOrDown && value < 0,
      'text-percent': params.withPercent
    }, this.getHeaderClass(params));
  }

  getHeaderClass(params: QuoteHeader) {
    let appendClass;
    appendClass = params.class ? params.class.reduce((acc, cur) => Object.assign({}, acc, { [cur]: true }), {}) : {};
    return Object.assign({}, appendClass);
  }

  getBlockSymbol(block) {
    return block.symbol;
  }

  constructor(
    private broadcast: BroadcastService,
    private router: Router,
    private http: CmHttp,
    private socket: SocketService,
    private user: UserService) {
    router.events.subscribe(this.successHandler, this.failureHandler);
    // login check
    this.user.loginStatusSub.subscribe((isLogined) => {
      this.isUserLogin = isLogined;
    });
  }

  // 是否显示搜索
  liveRouteStateArray = ["article", "articlelist", "subject", "live"];
  successHandler = (param) => {
    let reg = param["url"].match(/^\/([a-zA-Z]+[^\/\?])/);  // id, url, urlAfterRedirects
    let state = reg ? reg[1] : null;
    this.currentTab = this.liveRouteStateArray.indexOf(state) > -1 ? "live" : (state ? state : "live");
    // console.debug("Router Handler: ", param.url, reg, state, this.currentTab);
  }

  failureHandler = (err) => {
    console.warn('route state change error: ', err);
  }

  openStock(quote) {
    let symbol = quote.symbol.replace(".", "_");
    this.router.navigate(["/stock", symbol]);

    // 通知stock.component众赢投顾指标均不显示
    let zytgTarget = document.getElementById("zytgTarget");
    let zytgLis = zytgTarget.getElementsByTagName("li");
    for (let i = 0; i < zytgLis.length; i++) {
      if (this.hasClass(zytgLis[i], "active")) {
        zytgLis[i].click();
      }
    }
  }

  hasClass(elem, cls) {
    cls = cls || "";
    if (cls.replace(/\s/g, "").length == 0) return false; //当cls没有参数时，返回false
    return new RegExp(" " + cls + " ").test(" " + elem.className + " ");
  }


  isCurrent(tab) {
    return this.currentTab === tab.type;
  }

  OnClick(tab) {
    this.currentTab = tab.type;
  }

  // 是否IE, 用于显示图标激活样式
  isIE;
  ngOnInit() {
    // 判断是否IE
    let browser = new UAParser().getBrowser();
    this.isIE = browser.name === "IE";
    console.debug('is IE: ', this.isIE);

    this.indexStockSubscription = this.indexSub.switchMap(quotation => {
      return this.http.get(`${STOCKURL}/api/v2/sc/stocks/quotation${getParams(quotation)}`, {})
    })
      .subscribe(res => {
        console.debug("%c indexStockSubscription index list res: ", "color:#09f", res);
        // res = res.filter(req => !!req.change_rate);
        if (res.isError || !res.data)
           return;
        this.blockData = res.data;
        if (this.indexSymbolList) {
          this.socket.emit('sub', { channel: 'watchlist', symbols: this.indexSymbolList });
        }
      }, err => console.log('index quotation err:', err));

    // 动态更新股指的数据
    this.socket.on("watchlist", data => {
      let updateData = data; //adapt to v2 api
      //let updateData = Object.keys(data).map(key => data[key]).reduce(first => first);

      this.blockData = this.blockData.map(row => {
        if (row['symbol'] === updateData['symbol']) {
          row = _.merge({}, row, updateData);
        }
        return row;
      });
    });

    Observable.interval(1000).subscribe(_ => this.theBigBen = new Date());
  }

  ngAfterViewInit() {
    this.indexSub.next(this.indexSymbolList);
  }

  ngOnDestroy() {
    this.indexStockSubscription ? this.indexStockSubscription.unsubscribe() : null;
  }

  switchModal(action: string) {
    this.modalFlag = action;
  }
}